#!/usr/bin/ruby -d


require 'tstorage'
require '/var/lib/gems/1.8/gems/chronic-0.2.3/lib/chronic'

class Mail

  def process
    if (header['From'] =~ /<(\S+@\S+)>/)
      @submitter = $1
    else
      raise ArgumentError, "Unknown submitter", header['From']
    end
    @subject   = header['Subject']
    @request   = header['To']
    if @request =~ /submit/i 
      @submit = 1
    elsif @request =~ /remind/i
      @submit = 0
    else
      raise ArgumentError,
            "Unknown destination address in Mail.initialize.",
            caller
    end

    @date = nil
    body.each do |line|
      break if (line =~ /--\n/ || line =~ /^thank\w*\n/)
      if line =~ /^Date:\s*(.+)$/
        something = $1
        if !(@date = Chronic.parse(something).to_i)
          raise ArgumentError, "Wrong date. YYYY-MM-DD or day of week expected."
        end
      end
    end
    if !(@date)
      raise ArgumentError, "No Date: directive."
    end
    if @submit
      tstor = TaskStorage.instance
      tstor.store(@submitter, @subject, @date)
    else
      rem = Reminder.new(@submitter, @subject)
      smtp_code = rem.send
#      if (smtp_code =~ /^2/)
        # Its OK. Report somwhere.
#      end
    end
  end
end

